#!/usr/bin/env node

const fs = require('fs').promises;
const path = require('path');
const iconv = require('iconv-lite');

/**
 * Convert MD files from GBK to UTF-8 encoding
 */
async function convertMdEncoding() {
  try {
    const grammarDir = path.join(__dirname, '../resources/grammar');
    
    // Check if grammar directory exists
    try {
      await fs.access(grammarDir);
    } catch (err) {
      console.error('Grammar directory not found:', grammarDir);
      process.exit(1);
    }
    
    // Read all files in the grammar directory
    const files = await fs.readdir(grammarDir);
    const mdFiles = files.filter(file => file.endsWith('.txt'));
    
    console.log(`Found ${mdFiles.length} MD files to convert`);
    
    let convertedCount = 0;
    let errorCount = 0;
    
    for (const file of mdFiles) {
      try {
        const filePath = path.join(grammarDir, file);
        
        // Read file with GBK encoding
        const contentBuffer = await fs.readFile(filePath);
        const decodedContent = iconv.decode(contentBuffer, 'gbk');
        
        // Write file with UTF-8 encoding
        await fs.writeFile(filePath, decodedContent, 'utf-8');
        
        convertedCount++;
        console.log(`Converted: ${file}`);
      } catch (error) {
        errorCount++;
        console.error(`Error converting ${file}:`, error.message);
      }
    }
    
    console.log(`Successfully converted ${convertedCount} MD files`);
    if (errorCount > 0) {
      console.log(`Failed to convert ${errorCount} MD files`);
    }
  } catch (error) {
    console.error('Error in convertMdEncoding:', error);
    process.exit(1);
  }
}

// Run the conversion if this script is executed directly
if (require.main === module) {
  convertMdEncoding();
}

module.exports = convertMdEncoding;